use crate::models::attribute_group_translations::{CreateParams, Model};
use axum::debug_handler;
use loco_rs::prelude::*;

#[debug_handler]
async fn create(
    State(ctx): State<AppContext>,
    Json(params): Json<CreateParams>,
) -> Result<Response> {
    let translation = Model::create(&ctx.db, &params).await?;
    format::json(translation)
}

#[debug_handler]
async fn find_by_id(State(ctx): State<AppContext>, Path(id): Path<String>) -> Result<Response> {
    let translation = Model::find_by_id(&ctx.db, &id).await?;
    format::json(translation)
}

#[debug_handler]
async fn find_by_attribute_group_id(
    State(ctx): State<AppContext>,
    Path(group_id): Path<String>,
) -> Result<Response> {
    let translations = Model::find_by_attribute_group_id(&ctx.db, &group_id).await?;
    format::json(translations)
}

#[debug_handler]
async fn find_by_locale(
    State(ctx): State<AppContext>,
    Path(locale): Path<String>,
) -> Result<Response> {
    let translations = Model::find_by_locale(&ctx.db, &locale).await?;
    format::json(translations)
}

#[debug_handler]
async fn update_name(
    State(ctx): State<AppContext>,
    Path(id): Path<String>,
    Json(name): Json<String>,
) -> Result<Response> {
    let translation = Model::find_by_id(&ctx.db, &id).await?;
    let translation = translation
        .into_active_model()
        .update_name(&ctx.db, name)
        .await?;
    format::json(translation)
}

#[debug_handler]
async fn delete_by_id(State(ctx): State<AppContext>, Path(id): Path<String>) -> Result<Response> {
    let translation = Model::find_by_id(&ctx.db, &id).await?;
    translation.delete(&ctx.db).await?;
    format::json(())
}

pub fn routes() -> Routes {
    Routes::new()
        .prefix("attribute-group-translations")
        .add("/", post(create))
        .add("/:id", get(find_by_id))
        .add("/group/:group_id", get(find_by_attribute_group_id))
        .add("/locale/:locale", get(find_by_locale))
        .add("/:id/name", put(update_name))
        .add("/:id", delete(delete_by_id))
}
